package com.yuyou.fn.timer.task;

import com.github.wens.mybatisplus.examples.Example;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import com.xxl.job.core.log.XxlJobLogger;
import com.yuyou.fn.common.util.BigDecimals;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.settlement.constant.FeeCategoryEnum;
import com.yuyou.fn.settlement.constant.FeeShareStatus;
import com.yuyou.fn.settlement.constant.FeeStatus;
import com.yuyou.fn.settlement.entity.Fee;
import com.yuyou.fn.settlement.service.IFeeService;
import com.yuyou.fn.settlement.service.ISettlementService;
import com.yuyou.fn.tradingservice.service.IServiceOrderItemService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@JobHander(value="LeaseFeeShareTask")
@Component
public class LeaseFeeShareTask extends IJobHandler {

    @Resource
    private IFeeService feeService ;

    @Resource
    private ISettlementService settlementService ;

    @Resource
    private IServiceOrderItemService serviceOrderItemService ;

    @Resource
    private RedisTemplate<String,String> redisTemplate ;


    @Override
    public ReturnT<String> execute(String... params) throws Exception {

        Date currentDate  = DateUtils.addDays( TimeUtils.now(), 0 );

        //查找租赁
        Example<Fee> feeExample = Fee.createExample();
        feeExample.createCriteria().andEqualTo("feeCategoryId" , FeeCategoryEnum.LEAVE.id )
                .andEqualTo("status" , FeeStatus.AUDITED.ordinal() )
                .andEqualTo("shareStatus" , FeeShareStatus.NOT_SHARE.ordinal() ).andIsNotNull("busId").andLessThan("shareStart",currentDate);

        List<Fee> feeList = feeService.findListByExample(feeExample);

        boolean hasFail = false ;
        for(Fee fee : feeList ){

            if( fee.getShareStart() == null || fee.getShareEnd() == null ){
                XxlJobLogger.log("无法处理，信息不完整: {0}" , fee.getFeeId());
                continue;
            }
            if (fee.getBusId()!=null){
                try{
                    handle(currentDate, fee);
                }catch (Exception e){
                    hasFail = true ;
                    XxlJobLogger.log("处理失败:feeId={0},error={1}" , fee.getFeeId() , Utils.getExceptionStackTrace(e));
                }
            }else {

            }


        }

        return hasFail ? ReturnT.FAIL :  ReturnT.SUCCESS;
    }

    private void handle(Date currentDate, Fee fee) {
        int days =  TimeUtils.durationOfDay( fee.getShareStart(),fee.getShareEnd() );
        BigDecimal oneDayShareAmount = BigDecimals.calProportion(fee.getAmount(), BigDecimal.ONE,BigDecimal.valueOf(days));

        int sharedDays =  Utils.parseInt( (String)redisTemplate.opsForHash().get("fee:share:day" , String.valueOf(fee.getFeeId()))) ;
        BigDecimal totalSharedAmount = BigDecimal.ZERO ;
        while (sharedDays < days ){
            Date date = DateUtils.addDays(fee.getShareStart() , sharedDays );
            if(DateUtils.isSameDay(date, currentDate )){
                break;
            }
            BigDecimal amount = serviceOrderItemService.countLeaseOneDayByOrderItemId(fee.getBusId(),date );
            settlementService.shareFee(fee.getMainAccountId(),fee.getFeeCategoryId(),fee.getReceiverMainAccountId(),amount,"分摊【"+fee.getRemark()+"】-" + Utils.formatDate(date,"yyyy-MM-dd")  ,fee.getFeeId(),date );
            sharedDays++;
            totalSharedAmount = totalSharedAmount.add(oneDayShareAmount);
        }

        fee.setSharedAmount(fee.getSharedAmount().add(totalSharedAmount));
        if(sharedDays == days){
            fee.setShareStatus(FeeShareStatus.SHAREED.ordinal());
        }
        feeService.updateSelectiveById(fee);
        redisTemplate.opsForHash().put("fee:share:day" , String.valueOf(fee.getFeeId()),String.valueOf(sharedDays) );
    }


}
